package com.gyc.game.cchess.model;

import com.gyc.game.cchess.GameView;

public class SearchEngineAlphaBeta extends SearchEngineAbstract {

	public SearchEngineAlphaBeta() {
		super();
	}

	public ChessMove SearchAGoodMove(ChessBoardBitPlanes position) {

		bestMove = null;

		eveluator.count = 0;

		try {
			CurPosition = position.copy();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

		alphabeta(0, -20000, 20000);

		return bestMove;

	}

	int alphabeta(int step, int alpha, int beta) {

		int score;

		int i = IsGameOver(step);// 0

		if (i != 0) {
			return i;
		}

		final boolean isRed = ((step) % 2) != 0;

		if (step == this.searchDepth) {

			return eveluator.eveluate(CurPosition, isRed);
		}

		int cnt = CurPosition.generatePossibleMoves((byte) ((step) % 2) != 0,
				step);

		for (int mi = 0; mi < cnt; mi++) {

			if (step == 0) {
				this.getUihandler().sendEmptyMessage(GameView.message_inter);
			}

			ChessMove chessMove = (ChessMove) CurPosition.m_MoveList[step][mi];

			CurPosition.makeMove(chessMove, true);

			score = -alphabeta(step + 1, -beta, -alpha);

			CurPosition.unMakeMove(chessMove);

			if (score > alpha) {
				alpha = score;
				if (step == 0) {
					bestMove = chessMove;
				}
			}

			if (alpha >= beta) {
				break;
			}
		}
		return alpha;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
}
